package _2_两数相加;

import org.junit.jupiter.api.Test;

class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode out = new ListNode(0);
        ListNode tmp = out;
        int l1Int = 0;
        int l2Int = 0;
        int nextInt = 0;
        while (true) {
            if (l1 == null && l2 == null && nextInt == 0)
                break;

            if (l1 != null) {
                l1Int = l1.val;
                l1 = l1.next;
            } else {
                l1Int = 0;
            }

            if (l2 != null) {
                l2Int = l2.val;
                l2 = l2.next;
            } else {
                l2Int = 0;
            }

            int sum = l1Int + l2Int + nextInt;
            int yu = sum % 10;
            ListNode node = new ListNode(yu);
            tmp.next = node;
            tmp = tmp.next;

            nextInt = sum / 10;
        }
        out = out.next;
        return out;
    }

    /**
     * 测试用例:[2,4,3]
     * [5,6,4]
     */
    @Test
    public void test1() {
        ListNode l1_2 = new ListNode(2);
        ListNode l1_4 = new ListNode(4);
        ListNode l1_3 = new ListNode(3);
        l1_2.next = l1_4;
        l1_4.next = l1_3;

        ListNode l2_5 = new ListNode(5);
        ListNode l2_6 = new ListNode(6);
        ListNode l2_4 = new ListNode(4);
        l2_5.next = l2_6;
        l2_6.next = l2_4;
        ListNode out = addTwoNumbers(l1_2, l2_5);
        System.out.println(out);
    }

    /**
     * 测试用例:[9]
     * [1,9,9,9,9,9,9,9,9,9]
     * 测试结果:[8,0,4,5,6,0,0,1,4,1]
     * 期望结果:[0,0,0,0,0,0,0,0,0,0,1]
     */
    @Test
    public void test2() {
        ListNode l1 = new ListNode(9);
        int a2[] = {1, 9, 9, 9, 9, 9, 9, 9, 9, 9};
        ListNode l2 = new ListNode(a2[0]);
        ListNode tmp = l2;
        for (int i = 1; i < a2.length; i++) {
            tmp.next = new ListNode(a2[i]);
            tmp = tmp.next;
        }

        System.out.println(l1);
        System.out.println(l2);
        ListNode out = addTwoNumbers(l1, l2);
        System.out.println(out);
    }
}